local Luaemo = fk.CreateSkill {
    name = "Luaemo",
    anim_type = "special",
    frequency = Skill.Compulsory,
}

Fk:loadTranslationTable{
    ["Luaemo"] = "恶魔",
    ["@@fuzou_shu-inarea"] = "鼠符咒",
    ["@@fuzou_niu-inarea"] = "牛符咒", 
    ["@@fuzou_hu-inarea"] = "虎符咒",
    ["@@fuzou_tu-inarea"] = "兔符咒",
    ["@@fuzou_long-inarea"] = "龙符咒",
    ["@@fuzou_she-inarea"] = "蛇符咒",
    ["@@fuzou_ma-inarea"] = "马符咒",
    ["@@fuzou_yang-inarea"] = "羊符咒",
    ["@@fuzou_hou-inarea"] = "猴符咒",
    ["@@fuzou_ji-inarea"] = "鸡符咒",
    ["@@fuzou_gou-inarea"] = "狗符咒",
    ["@@fuzou_zhu-inarea"] = "猪符咒",
    ["@@hu_shaneti"] = "虎-善体",
    ["@@hu_eti"] = "虎-恶体",
    ["@@yang_controlled"] = "羊-操控",
    ["@@hou_deputy"] = "猴-副将",
    ["#Luaemo-long"] = "龙符咒：对至多3名角色造成1点火焰伤害并弃置其装备",
    ["#yang-target"] = "羊符咒：选择一名角色操控其并进行额外回合",
    [":Luaemo"] = "锁定技，游戏开始时，回合开始时，当你受到伤害时从牌堆或弃牌堆随机装备一件装备并赋予其一个随机符咒效果，且当你受到伤害后随机失去一件装备并失去一点体力。" ..
    "<font color='grey'><b><br>符咒效果 " ..
    "<br>鼠：死亡时，失去此符咒改为休整一轮；" ..
    "<br>牛：造成伤害时伤害翻倍；" ..
    "<br>虎：每轮开始时切换善恶体，善体回复全场1血，恶体对全场造成1点火伤；" ..
    "<br>兔：出牌阶段，可以使用任意数量的杀；" ..
    "<br>龙：对至多3名角色造成1点火焰伤害，并弃置其所有装备牌；" ..
    "<br>蛇：受到伤害后直到回合开始时其他角色使用牌无法指定你为目标；" ..
    "<br>马：受到伤害时体力值和体力+1；" ..
    "<br>羊：每轮结束或当你死亡时，你操控一名角色执行一个额外回合；" ..
    "<br>猴：所有角色同时选择一张异性武将牌作为副将，且当一名角色受到伤害后，其随机变更其副将；" ..
    "<br>鸡：每轮开始时随机更换座位；" ..
    "<br>狗：濒死时体力回复至1点，失去1点体力上限 ；" ..
    "<br>猪：所有角色始终处于横置状态。</b></font>",
}

-- 符咒类型
local fuzou_types = {
    "shu", "niu", "hu", "tu", "long", "she", 
    "ma", "yang", "hou", "ji", "gou", "zhu"
}

-- 随机装备装备牌并赋予符咒
local function equipRandomWithFuzou(room, player)
    -- 收集所有装备牌
    local equip_cards = {}
    for _, id in ipairs(room.draw_pile) do
        local card = Fk:getCardById(id)
        if card.type == Card.TypeEquip then
            table.insert(equip_cards, id)
        end
    end
    for _, id in ipairs(room.discard_pile) do
        local card = Fk:getCardById(id)
        if card.type == Card.TypeEquip then
            table.insert(equip_cards, id)
        end
    end
    
    if #equip_cards > 0 then
        -- 随机选择一件装备
        local equip_id = equip_cards[math.random(#equip_cards)]
        local equip_card = Fk:getCardById(equip_id)
        
        -- 随机选择符咒类型
        local fuzou_type = fuzou_types[math.random(#fuzou_types)]
        
        -- 给装备添加符咒标记
        room:setCardMark(equip_card, "@@fuzou_" .. fuzou_type .."-inarea", 1)
        room:useCard({
            from = player,
            card = equip_card,
        })
        
        return fuzou_type
    end
end

-- 判断玩家是否拥有特定符咒
local function hasFuzou(player, fuzou_type)
    for _, id in ipairs(player:getCardIds("e")) do
        local card = Fk:getCardById(id)
        if card:getMark("@@fuzou_" .. fuzou_type .."-inarea") > 0 then
            return id
        end
    end
    return nil
end

-- 游戏开始时
Luaemo:addEffect(fk.GameStart, {
    can_trigger = function(self, event, target, player, data)
        return player:hasSkill(Luaemo.name)
    end,
    on_cost = Util.TrueFunc,
    on_use = function(self, event, target, player, data)
        equipRandomWithFuzou(player.room, player)
    end,
})

-- 回合开始时
Luaemo:addEffect(fk.TurnStart, {
    can_trigger = function(self, event, target, player, data)
        return target == player and player:hasSkill(Luaemo.name)
    end,
    on_cost = Util.TrueFunc,
    on_use = function(self, event, target, player, data)
        equipRandomWithFuzou(player.room, player)
    end,
})

-- 受到伤害时
Luaemo:addEffect(fk.DamageInflicted, {
    can_trigger = function(self, event, target, player, data)
        return target == player and player:hasSkill(Luaemo.name)
    end,
    on_cost = Util.TrueFunc,
    on_use = function(self, event, target, player, data)
        equipRandomWithFuzou(player.room, player)
    end,
})

-- 受到伤害后
Luaemo:addEffect(fk.Damaged, {
    can_trigger = function(self, event, target, player, data)
        return target == player and player:hasSkill(Luaemo.name)
    end,
    on_cost = Util.TrueFunc,
    on_use = function(self, event, target, player, data)
        local room = player.room
        -- 随机失去一件装备
        local equips = player:getCardIds("e")
        if #equips > 0 then
            local random_equip = equips[math.random(#equips)]
            room:throwCard({random_equip}, Luaemo.name, player, player)
        end
        -- 失去一点体力
        room:loseHp(player, 1, Luaemo.name)
    end,
})

-- 鼠符咒：死亡时改为休整一轮
Luaemo:addEffect(fk.Deathed, {
    is_delay_effect = true,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self.name, true, true) and hasFuzou(player, "shu")
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, id in ipairs(target:getCardIds("e")) do
		local card = Fk:getCardById(id)
        if card:getMark("@@fuzou_shu-inarea") == 1 then
			room:setCardMark(card, "@@fuzou_shu-inarea", 0)
        end
	end
    player.room:setPlayerProperty(player, "rest", 1) 
  end,
})

-- 牛符咒：造成伤害时翻倍
Luaemo:addEffect(fk.DamageCaused, {
    is_delay_effect = true,
    can_trigger = function(self, event, target, player, data)
        return target == player and hasFuzou(player, "niu")
    end,
    on_cost = Util.TrueFunc,
    on_use = function(self, event, target, player, data)
        data.damage = data.damage * 2
    end,
})

-- 虎符咒：每轮开始时切换善恶体
Luaemo:addEffect(fk.RoundStart, {
    is_delay_effect = true,
    can_trigger = function(self, event, target, player, data)
        return hasFuzou(player, "hu")
    end,
    on_cost = Util.TrueFunc,
    on_use = function(self, event, target, player, data)
        local room = player.room
        if player:getMark("@@hu_shaneti") > 0 then
            -- 切换到恶体
            room:setPlayerMark(player, "@@hu_shaneti", 0)
            room:setPlayerMark(player, "@@hu_eti", 1)
            -- 对全场造成火伤
            for _, p in ipairs(room.alive_players) do
                room:damage{
                    from = player,
                    to = p,
                    damage = 1,
                    damageType = fk.FireDamage,
                    skillName = Luaemo.name,
                }
            end
        else
            -- 切换到善体
            room:setPlayerMark(player, "@@hu_shaneti", 1)  
            room:setPlayerMark(player, "@@hu_eti", 0)
            -- 全场回复1血
            for _, p in ipairs(room.alive_players) do
                room:recover{
                    who = p,
                    num = 1,
                    recoverBy = player,
                    skillName = Luaemo.name
                }
            end
        end
    end,
})

-- 兔符咒：出牌阶段可使用任意数量的杀
-- 这里需要通过targetMod实现，添加bypass_times函数
Luaemo:addEffect('targetmod', {
  bypass_times = function(self, player, skill, scope, card)
    if card and player:hasSkill(self.name) and skill.trueName == "slash_skill" -- FIXME
      and scope == Player.HistoryPhase and hasFuzou(player, "tu") and player.phase == Player.Play then
      return true
    end
  end,
})

-- 龙符咒：对至多3名角色造成火焰伤害并弃置装备
-- 这需要添加一个主动技能
Luaemo:addEffect("active", {
    prompt = "#Luaemo-long",
    can_use = function(self, player)
        return hasFuzou(player, "long") and player:usedSkillTimes("Luaemo_long", Player.HistoryPhase) == 0
    end,
    card_num = 0,
    min_target_num = 1,
    max_target_num = 3,
    card_filter = Util.FalseFunc,
    target_filter = function(self, player, to_select, selected)
        return #selected < 3 and to_select ~= player
    end,
    on_use = function(self, room, effect)
        local player = effect.from
        for _, target_id in ipairs(effect.tos) do
            room:damage{
                from = player,
                to = target_id,
                damage = 1,
                damageType = fk.FireDamage,
                skillName = Luaemo.name,
            }
            local equips = target_id:getCardIds("e")
            if #equips > 0 then
                room:throwCard(equips, Luaemo.name, target_id, target_id)
            end
        end
    end,
})

-- 蛇符咒：受伤后其他角色无法指定你为目标
Luaemo:addEffect("prohibit", {
    is_prohibited = function(self, from, to)
        return to:hasSkill(Luaemo.name) and to:isWounded() and from ~= to and hasFuzou(to, "she")
    end,
})

-- 马符咒：受到伤害时体力值和体力+1
Luaemo:addEffect(fk.DamageInflicted, {
    is_delay_effect = true,
    can_trigger = function(self, event, target, player, data)
        return target == player and hasFuzou(player, "ma")
    end,
    on_cost = Util.TrueFunc,
    on_use = function(self, event, target, player, data)
        local room = player.room
        room:changeMaxHp(player, 1)
        room:recover{
            who = player,
            num = 1,
            recoverBy = player,
            skillName = Luaemo.name
        }
    end,
})

-- 羊符咒：每轮结束或当你死亡时，你操控一名角色执行一个额外回合
Luaemo:addEffect(fk.RoundEnd, {
    is_delay_effect = true,
    can_trigger = function(self, event, target, player, data)
        return player:hasSkill(Luaemo.name) and hasFuzou(player, "yang")
    end,
    on_cost = Util.TrueFunc,
    on_use = function(self, event, target, player, data)
        local room = player.room
        local target_id = room:askToChoosePlayers(player, {
            targets = room:getOtherPlayers(player),
            min_num = 1,
            max_num = 1,
            prompt = "#yang-target",
            skill_name = Luaemo.name,
            cancelable = false
        })
        if #target_id > 0 then
            local target = target_id[1]
            player:control(target)
            room:setPlayerMark(target, "@@yang_controlled", 1)
            target:gainAnExtraTurn(true, Luaemo.name)
            
            
        end
    end,
})

Luaemo:addEffect(fk.EventPhaseEnd, {
    is_delay_effect = true,
    mute = true,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(Luaemo.name) and 
           target.phase == Player.Finish and 
           target:getMark("@@yang_controlled") > 0
  end,
  
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(target, "@@yang_controlled", 0)
    -- 恢复控制权
    target:control(target)
  end,
})

Luaemo:addEffect(fk.Deathed, {
    is_delay_effect = true,
    can_trigger = function(self, event, target, player, data)
        return target == player and player:hasSkill(Luaemo.name) and hasFuzou(player, "yang")
    end,
    on_cost = Util.TrueFunc,
    on_use = function(self, event, target, player, data)
        local room = player.room
        local target_id = room:askToChoosePlayers(player, {
            targets = room:getOtherPlayers(player),
            min_num = 1,
            max_num = 1,
            prompt = "#yang-target",
            skill_name = Luaemo.name,
            cancelable = false
        })
        if #target_id > 0 then
            local target = target_id[1]
            player:control(target)
            target:gainAnExtraTurn(true, Luaemo.name)
            
        end
    end,
})

-- 猴符咒：所有角色同时选择一张异性武将牌作为副将，且当一名角色受到伤害后，其随机变更其副将
local function assignRandomDeputy(room, player, target_player)
  room:doIndicate(player.id, {target_player.id})
  local generals = table.filter(room.general_pile, function(name)
    return not table.contains({"shengzhu"}, name)
  end)
  local general = table.random(generals)
  if general then
    table.removeOne(room.general_pile, general)
    if target_player.deputyGeneral ~= "" then
      room:returnToGeneralPile({target_player.deputyGeneral})
    end
    room:changeHero(target_player, general, false, true, true, false, false)
  end
end

Luaemo:addEffect(fk.AfterCardsMove, {
    is_delay_effect = true,
    can_trigger = function(self, event, target, player, data)
      if not player:hasSkill(self) or player.dead then return false end
      for _, move in ipairs(data) do
        if move.to and move.to == player and move.toArea == Card.PlayerEquip then
          for _, info in ipairs(move.moveInfo) do
            if Fk:getCardById(info.cardId):getMark("@@fuzou_hou-inarea") == 1 then
              return true
            end
          end
        end
      end
    end,
    on_cost = Util.TrueFunc,
    on_use = function(self, event, target, player, data)
        local room = player.room
        for _, target_id in ipairs(room:getAlivePlayers()) do
            room:setPlayerMark(target_id, "@@hou_deputy", 1)
        end
        local generalNum = room:getSettings("generalNum")
        local tos = room:getOtherPlayers(player)
        local req = Request:new(tos, "AskForGeneral")
        req.focus_text = Luaemo.name
        local returnGenerals = {}
        for i, p in ipairs(tos) do
            local generals = room:findGenerals(function (g)
                if Fk.generals[g].gender == General.Bigender or Fk.generals[p.general].gender == General.Bigender then return true end
                return Fk.generals[g].gender ~= Fk.generals[p.general].gender
            end,generalNum)
            table.insertTableIfNeed(returnGenerals,generals)
            req:setData(p, { generals, 1 })
            req:setDefaultReply(p, table.random(generals, 1))
        end
        req:ask()

        for _, p in ipairs(tos) do
            local result = req:getResult(p)
            table.removeOne(returnGenerals,result[1])
            if p.deputyGeneral ~= "" then
                table.insertIfNeed(returnGenerals,p.deputyGeneral)
            end
            --room:prepareGeneral(p, p.general, result[1], true)
            room:changeHero(p,result[1],false,true,true,true,false)
        end
        room:returnToGeneralPile(returnGenerals)
    end,
})

Luaemo:addEffect(fk.AfterCardsMove, {
    is_delay_effect = true,
    can_trigger = function(self, event, target, player, data)
      if not player:hasSkill(self) or player.dead then return false end  
        for _, move in ipairs(data) do
            for _, info in ipairs(move.moveInfo) do
                if (info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip) then
                    if Fk:getCardById(info.cardId):getMark("@@fuzou_hou-inarea") == 1 then
                        return true
                    end
                end
            end
        end
    end,
    on_cost = Util.TrueFunc,
    on_use = function(self, event, target, player, data)
        local room = player.room
        for _, target_id in ipairs(room:getAlivePlayers()) do
            room:setPlayerMark(target_id, "@@hou_deputy", 0)
        end
    end,
})

Luaemo:addEffect(fk.Damaged, {
    is_delay_effect = true,
    can_trigger = function(self, event, target, player, data)
        return target:getMark("@@hou_deputy") > 0 and hasFuzou(player, "hou")
    end,
    on_cost = Util.TrueFunc,
    on_use = function(self, event, target, player, data)
        local room = player.room
        assignRandomDeputy(room, player, target)
    end,
})

-- 鸡符咒：每轮开始时随机更换座位
Luaemo:addEffect(fk.RoundStart, {
    is_delay_effect = true,
    can_trigger = function(self, event, target, player, data)
        return player:hasSkill(Luaemo.name) and hasFuzou(player, "ji")
    end,
    on_cost = Util.TrueFunc,
    on_use = function(self, event, target, player, data)
        local room = player.room
        -- 获取所有存活玩家
        local alive_players = {}
        for _, p in ipairs(room.alive_players) do
            table.insert(alive_players, p)
        end
        
        -- 打乱顺序
        for i = #alive_players, 2, -1 do
            local j = math.random(i)
            alive_players[i], alive_players[j] = alive_players[j], alive_players[i]
        end
        
        -- 重新安排座位
        for i = 1, #alive_players do
            local next_index = i % #alive_players + 1
            room:swapSeat(alive_players[i], alive_players[next_index])
        end
    end,
})

-- 狗符咒：濒死时体力回复至1点，失去1点体力上限
Luaemo:addEffect(fk.EnterDying, {
    is_delay_effect = true,
    can_trigger = function(self, event, target, player, data)
        return target == player and hasFuzou(player, "gou") and player.hp <= 0
    end,
    on_cost = Util.TrueFunc,
    on_use = function(self, event, target, player, data)
        local room = player.room
        room:changeMaxHp(player, -1)
        room:recover{
            who = player,
            num = 1 - player.hp,
            recoverBy = player,
            skillName = Luaemo.name
        }
    end,
})

-- 猪符咒：所有角色始终处于横置状态
-- 确保在任何角色回合开始时，所有角色都是横置状态（针对猪符咒）
Luaemo:addEffect(fk.AfterCardsMove, {
    is_delay_effect = true,
    can_trigger = function(self, event, target, player, data)
      if not player:hasSkill(self) or player.dead then return false end
      for _, move in ipairs(data) do
        if move.to and move.to == player and move.toArea == Card.PlayerEquip then
          for _, info in ipairs(move.moveInfo) do
            if Fk:getCardById(info.cardId):getMark("@@fuzou_zhu-inarea") == 1 then
              return true
            end
          end
        end
      end
    end,
    on_cost = Util.TrueFunc,
    on_use = function(self, event, target, player, data)
        local room = player.room
        for _, target_id in ipairs(room:getAlivePlayers()) do
            target_id:setChainState(true)
        end
    end,
})



-- 额外补充：确保猪符咒对尝试解除横置状态的情况也生效
Luaemo:addEffect(fk.BeforeChainStateChange, {
  anim_type = "negative",
  is_delay_effect = true,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(Luaemo.name) and target.chained and hasFuzou(player, "zhu")
  end,
  on_use = function (self, event, target, player, data)
    data.prevented = true
  end,
})



-- 玩家失去恶魔技能时清除所有符咒效果
Luaemo:addLoseEffect(function(self, player)
    local room = player.room
    -- 清除所有标记
    room:setPlayerMark(player, "@@zhu_hengzhi", 0)
    room:setPlayerMark(player, "@@hu_shaneti", 0)
    room:setPlayerMark(player, "@@hu_eti", 0)
    room:setPlayerMark(player, "@@she_wufazhi", 0)
    room:setPlayerMark(player, "@@hou_deputy", 0)
    room:setPlayerMark(player, "@@liejiao_sum", 0)
    
    -- 清除所有装备上的符咒标记
    for _, id in ipairs(player:getCardIds("e")) do
        local card = Fk:getCardById(id)
        for _, fuzou_type in ipairs(fuzou_types) do
            if card:getMark("@fuzou_" .. fuzou_type) > 0 then
                room:setCardMark(card, "@fuzou_" .. fuzou_type, 0)
            end
        end
    end
end)


return Luaemo 